package com.mage.servlet;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mage.bean.User;
import com.mage.dao.impl.UserDaoImpl;




@WebServlet("/LoginCheck")
public class LoginCheck extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

    public LoginCheck() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("---------------------");
		User user = null;
		ResultSet rs = null;
		String username = request.getParameter("username");  //从request对象中取出名称为userName所对应的值
		String password  = request.getParameter("password");
		String usertype = request.getParameter("usertype");
		request.getSession().setAttribute("usertype", usertype);  //request.getSession()可以帮你得到HttpSession类型的对象，通常称之为session对象，session对象的作用域为一次会话，通常浏览器不关闭，保存的值就不会消失
		//setAttribute将输入的的usertype内容赋给左边的usertype。可以使用session.getAttribute("key");来取值，获得userName的值。
		try {
		user = new UserDaoImpl().searchUserForLogin(username, password, usertype);          //??????????????
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if(user == null) {  //如果不输入username或password或usertype中的任何一个，将会重新返回登陆页面
			request.getSession().setAttribute("message", "用户名或密码或用户类型错误！！！");
			response.sendRedirect("index.jsp");  //跳转到指定的URL地址后，也就是index.jsp页面
		}else { //如果全部输入了
			System.out.println("欢迎用户:"+user.getUsername());
			request.getSession().setAttribute("userid", user.getUserid());
			request.getSession().setAttribute("username", username);
			request.setAttribute("loginFlag", 1);
			if(usertype.equals("-1")) {
				request.getRequestDispatcher("/Super/Super_about.jsp").forward(request, response);//请求转发到指定URL（管理者页面）
			}else if(usertype.equals("1")) {
				request.getRequestDispatcher("/Super/User_about.jsp").forward(request, response); //请求转发到指定URL（会员页面）
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
